package cn.kbyue.oauth2jwt.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;

/**
 * @author XL
 * @version 0.1
 * @date 2021/7/25 21:19
 */
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class OAuthResourceConfig extends ResourceServerConfigurerAdapter {

    private static final String RESOURCE_ID = "product_api";

    @Autowired
    JwtDecoder jwtDecoder;

    @Bean
    public ResourceServerTokenServices tokenService() {
        RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
        remoteTokenServices.setCheckTokenEndpointUrl("http://localhost:10021/oauth/check_token");
        remoteTokenServices.setClientId("baidu");
        remoteTokenServices.setClientSecret("123456");
        return remoteTokenServices;
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources
                .resourceId(RESOURCE_ID)
                .tokenServices(tokenService())
                .stateless(true);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                // .antMatchers("/**").access("#oauth2.hasAnyScope('read')")
                .anyRequest().authenticated()
                .and()
                .sessionManagement()
                // 设置session为无状态  提升效率
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .oauth2ResourceServer()
                .jwt();
                // .jwtAuthenticationConverter(jwt -> {
                //     Set<SimpleGrantedAuthority> authorities = ((Collection<String>) jwt.getClaims().get("authorities"))
                //             .stream()
                //             .map(SimpleGrantedAuthority::new)
                //             .collect(Collectors.toSet());
                //     return new JwtAuthenticationToken(jwt, authorities);
                // });
    }

}
